<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
  <meta name="theme-color" content="#222">
  <meta name="generator" content="Hexo 5.4.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

  <link rel="stylesheet" href="/css/main.css">



  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.2/css/all.min.css">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css">

  <script class="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {
      "hostname": "holidaypenguin.gitee.io",
      "root": "/",
      "images": "/images",
      "scheme": "Mist",
      "version": "8.2.2",
      "exturl": false,
      "sidebar": {
        "position": "right",
        "display": "always",
        "padding": 18,
        "offset": 12
      },
      "copycode": true,
      "bookmark": {
        "enable": false,
        "color": "#222",
        "save": "auto"
      },
      "fancybox": false,
      "mediumzoom": false,
      "lazyload": false,
      "pangu": false,
      "comments": {
        "style": "tabs",
        "active": null,
        "storage": true,
        "lazyload": false,
        "nav": null
      },
      "motion": {
        "enable": true,
        "async": true,
        "transition": {
          "post_block": "fadeIn",
          "post_header": "fadeInDown",
          "post_body": "fadeInDown",
          "coll_header": "fadeInLeft",
          "sidebar": "slideUpIn"
        }
      },
      "prism": false,
      "i18n": {
        "placeholder": "搜索...",
        "empty": "没有找到任何搜索结果：${query}",
        "hits_time": "找到 ${hits} 个搜索结果（用时 ${time} 毫秒）",
        "hits": "找到 ${hits} 个搜索结果"
      },
      "path": "/search.xml",
      "localsearch": {
        "enable": true,
        "trigger": "auto",
        "top_n_per_article": 1,
        "unescape": false,
        "preload": false
      }
    };
  </script>
  <meta property="og:type" content="article">
  <meta property="og:title" content="现代浏览器内部揭秘 part 4">
  <meta property="og:url" content="https://holidaypenguin.gitee.io/blob/2021-06-30-part-4-of-modern-browser/index.html">
  <meta property="og:site_name" content="HolidayPenguin">
  <meta property="og:locale" content="zh_CN">
  <meta property="og:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/16687fced9601c8b">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/16687fdfaf0acaf8">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/1668a69b2bd34e88">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/1668a69b2e688711">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/1668a69b2c870fb4">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/1668a69b295ae0bd">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/1668a69b28e7b10f">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/1668a69b2dbf1cb4">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/1668a69be9b80e4c">
  <meta property="og:image" content="https://holidaypenguin.gitee.io/images/FrontEnd/modern-browser/1668a69bf0a981cc">
  <meta property="article:published_time" content="2021-06-30T07:41:32.000Z">
  <meta property="article:modified_time" content="2021-06-30T07:41:32.000Z">
  <meta property="article:author" content="holidaypenguin">
  <meta property="article:tag" content="FrontEnd">
  <meta name="twitter:card" content="summary">
  <meta name="twitter:image" content="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io">


  <link rel="canonical" href="https://holidaypenguin.gitee.io/blob/2021-06-30-part-4-of-modern-browser/">


  <script class="page-configurations">
    // https://hexo.io/docs/variables.html
    CONFIG.page = {
      sidebar: "",
      isHome: false,
      isPost: true,
      lang: 'zh-CN'
    };
  </script>
  <title>现代浏览器内部揭秘 part 4 | HolidayPenguin</title>





  <noscript>
    <style>
      body {
        margin-top: 2rem;
      }

      .use-motion .menu-item,
      .use-motion .sidebar,
      .use-motion .post-block,
      .use-motion .pagination,
      .use-motion .comments,
      .use-motion .post-header,
      .use-motion .post-body,
      .use-motion .collection-header {
        visibility: visible;
      }

      .use-motion .header,
      .use-motion .site-brand-container .toggle,
      .use-motion .footer {
        opacity: initial;
      }

      .use-motion .site-title,
      .use-motion .site-subtitle,
      .use-motion .custom-logo-image {
        opacity: initial;
        top: initial;
      }

      .use-motion .logo-line {
        transform: scaleX(1);
      }

      .search-pop-overlay,
      .sidebar-nav {
        display: none;
      }

      .sidebar-panel {
        display: block;
      }
    </style>
  </noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner">
        <div class="site-brand-container">
          <div class="site-nav-toggle">
            <div class="toggle" aria-label="切换导航栏" role="button">
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
              <span class="toggle-line"></span>
            </div>
          </div>

          <div class="site-meta">

            <a href="/" class="brand" rel="start">
              <i class="logo-line"></i>
              <h1 class="site-title">HolidayPenguin</h1>
              <i class="logo-line"></i>
            </a>
          </div>

          <div class="site-nav-right">
            <div class="toggle popup-trigger">
              <i class="fa fa-search fa-fw fa-lg"></i>
            </div>
          </div>
        </div>



        <nav class="site-nav">
          <ul class="main-menu menu">
            <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li>
            <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li>
            <li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li>
            <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
            <li class="menu-item menu-item-search">
              <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
              </a>
            </li>
          </ul>
        </nav>



        <div class="search-pop-overlay">
          <div class="popup search-popup">
            <div class="search-header">
              <span class="search-icon">
                <i class="fa fa-search"></i>
              </span>
              <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off" maxlength="80" placeholder="搜索..." spellcheck="false" type="search" class="search-input">
              </div>
              <span class="popup-btn-close" role="button">
                <i class="fa fa-times-circle"></i>
              </span>
            </div>
            <div class="search-result-container no-result">
              <div class="search-result-icon">
                <i class="fa fa-spinner fa-pulse fa-5x"></i>
              </div>
            </div>

          </div>
        </div>

      </div>


      <div class="toggle sidebar-toggle" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
      </div>

      <aside class="sidebar">

        <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
          <ul class="sidebar-nav">
            <li class="sidebar-nav-toc">
              文章目录
            </li>
            <li class="sidebar-nav-overview">
              站点概览
            </li>
          </ul>

          <div class="sidebar-panel-container">
            <!--noindex-->
            <div class="post-toc-wrap sidebar-panel">
              <div class="post-toc animated">
                <ol class="nav">
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%94%A8%E6%88%B7%E8%BE%93%E5%85%A5%E8%A1%8C%E4%B8%BA%E4%B8%8E%E5%90%88%E6%88%90%E5%99%A8"><span class="nav-number">1.</span> <span class="nav-text">用户输入行为与合成器</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%B5%8F%E8%A7%88%E5%99%A8%E8%A7%86%E8%A7%92%E4%B8%8B%E7%9A%84%E8%BE%93%E5%85%A5%E4%BA%8B%E4%BB%B6"><span class="nav-number">2.</span> <span class="nav-text">浏览器视角下的输入事件</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%90%88%E6%88%90%E5%99%A8%E6%8E%A5%E6%94%B6%E8%BE%93%E5%85%A5%E4%BA%8B%E4%BB%B6"><span class="nav-number">3.</span> <span class="nav-text">合成器接收输入事件</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E7%90%86%E8%A7%A3%E9%9D%9E%E7%AB%8B%E5%8D%B3%E5%8F%AF%E6%BB%9A%E5%8A%A8%E5%8C%BA"><span class="nav-number">4.</span> <span class="nav-text">理解非立即可滚动区</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%AE%BE%E7%BD%AE%E4%BA%8B%E4%BB%B6%E5%A4%84%E7%90%86%E5%99%A8%E6%97%B6%E9%A1%BB%E6%B3%A8%E6%84%8F"><span class="nav-number">4.1.</span> <span class="nav-text">设置事件处理器时须注意</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%A3%80%E6%9F%A5%E4%BA%8B%E4%BB%B6%E6%98%AF%E5%90%A6%E5%8F%AF%E6%92%A4%E9%94%80"><span class="nav-number">5.</span> <span class="nav-text">检查事件是否可撤销</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%AE%9A%E4%BD%8D%E4%BA%8B%E4%BB%B6%E7%9B%AE%E6%A0%87"><span class="nav-number">6.</span> <span class="nav-text">定位事件目标</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%99%8D%E4%BD%8E%E5%BE%80%E4%B8%BB%E7%BA%BF%E7%A8%8B%E5%8F%91%E9%80%81%E4%BA%8B%E4%BB%B6%E7%9A%84%E9%A2%91%E7%8E%87"><span class="nav-number">7.</span> <span class="nav-text">降低往主线程发送事件的频率</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-getCoalescedEvents-%E8%8E%B7%E5%8F%96%E5%B8%A7%E5%86%85%E4%BA%8B%E4%BB%B6"><span class="nav-number">8.</span> <span class="nav-text">使用 getCoalescedEvents 获取帧内事件</span></a></li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%90%8E%E7%BB%AD%E6%AD%A5%E9%AA%A4"><span class="nav-number">9.</span> <span class="nav-text">后续步骤</span></a>
                    <ol class="nav-child">
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8-Lighthouse"><span class="nav-number">9.1.</span> <span class="nav-text">使用 Lighthouse</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AD%A6%E4%B9%A0%E5%A6%82%E4%BD%95%E8%AF%84%E6%B5%8B%E6%80%A7%E8%83%BD"><span class="nav-number">9.2.</span> <span class="nav-text">学习如何评测性能</span></a></li>
                      <li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%B8%BA%E4%BD%A0%E7%9A%84%E7%AB%99%E7%82%B9%E6%B7%BB%E5%8A%A0-Feature-Policy"><span class="nav-number">9.3.</span> <span class="nav-text">为你的站点添加 Feature Policy</span></a></li>
                    </ol>
                  </li>
                  <li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">10.</span> <span class="nav-text">总结</span></a></li>
                </ol>
              </div>
            </div>
            <!--/noindex-->

            <div class="site-overview-wrap sidebar-panel">
              <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
                <p class="site-author-name" itemprop="name">holidaypenguin</p>
                <div class="site-description" itemprop="description"></div>
              </div>
              <div class="site-state-wrap site-overview-item animated">
                <nav class="site-state">
                  <div class="site-state-item site-state-posts">
                    <a href="/archives/">

                      <span class="site-state-item-count">138</span>
                      <span class="site-state-item-name">日志</span>
                    </a>
                  </div>
                  <div class="site-state-item site-state-categories">
                    <a href="/categories/">

                      <span class="site-state-item-count">26</span>
                      <span class="site-state-item-name">分类</span></a>
                  </div>
                  <div class="site-state-item site-state-tags">
                    <a href="/tags/">

                      <span class="site-state-item-count">234</span>
                      <span class="site-state-item-name">标签</span></a>
                  </div>
                </nav>
              </div>
              <div class="links-of-author site-overview-item animated">
                <span class="links-of-author-item">
                  <a href="https://github.com/holidaypenguin" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;holidaypenguin" rel="noopener" target="_blank"><i class="github fa-fw"></i>GitHub</a>
                </span>
                <span class="links-of-author-item">
                  <a href="mailto:songshipeng2016@gmail.com" title="E-Mail → mailto:songshipeng2016@gmail.com" rel="noopener" target="_blank"><i class="envelope fa-fw"></i>E-Mail</a>
                </span>
              </div>



            </div>
          </div>
        </div>
      </aside>
      <div class="sidebar-dimmer"></div>


    </header>


    <div class="back-to-top" role="button">
      <i class="fa fa-arrow-up"></i>
      <span>0%</span>
    </div>

    <noscript>
      <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
    </noscript>


    <div class="main-inner post posts-expand">





      <div class="post-block">



        <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
          <link itemprop="mainEntityOfPage" href="https://holidaypenguin.gitee.io/blob/2021-06-30-part-4-of-modern-browser/">

          <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
            <meta itemprop="image" content="/images/avatar.gif">
            <meta itemprop="name" content="holidaypenguin">
            <meta itemprop="description" content="">
          </span>

          <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
            <meta itemprop="name" content="HolidayPenguin">
          </span>
          <header class="post-header">
            <h1 class="post-title" itemprop="name headline">
              现代浏览器内部揭秘 part 4
            </h1>

            <div class="post-meta-container">
              <div class="post-meta">
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-calendar"></i>
                  </span>
                  <span class="post-meta-item-text">发表于</span>

                  <time title="创建时间：2021-06-30 15:41:32" itemprop="dateCreated datePublished" datetime="2021-06-30T15:41:32+08:00">2021-06-30</time>
                </span>
                <span class="post-meta-item">
                  <span class="post-meta-item-icon">
                    <i class="far fa-folder"></i>
                  </span>
                  <span class="post-meta-item-text">分类于</span>
                  <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                    <a href="/categories/FrontEnd/" itemprop="url" rel="index"><span itemprop="name">FrontEnd</span></a>
                  </span>
                </span>


                <span id="/blob/2021-06-30-part-4-of-modern-browser/" class="post-meta-item leancloud_visitors" data-flag-title="现代浏览器内部揭秘 part 4" title="阅读次数">
                  <span class="post-meta-item-icon">
                    <i class="far fa-eye"></i>
                  </span>
                  <span class="post-meta-item-text">阅读次数：</span>
                  <span class="leancloud-visitors-count"></span>
                </span>
              </div>

              <div class="post-description">
                <!-- more -->
              </div>
            </div>
          </header>




          <div class="post-body" itemprop="articleBody">
            <p><a target="_blank" rel="noopener" href="https://github.com/jwenjian/visitor-count-badge"><img src="" data-original="https://visitor-badge.glitch.me/badge?page_id=holidaypenguin.gitee.io" alt="总访客数量"></a></p>
            <blockquote>
              <ul>
                <li>原文地址：<a target="_blank" rel="noopener" href="https://developers.google.com/web/updates/2018/09/inside-browser-part4">Inside look at modern web browser (part 4)</a></li>
                <li>原文作者：<a target="_blank" rel="noopener" href="https://developers.google.com/web/resources/contributors/kosamari">Mariko Kosaka</a></li>
                <li>译文出自：<a target="_blank" rel="noopener" href="https://github.com/xitu/gold-miner">掘金翻译计划</a> <a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903695600058375">[译] 现代浏览器内部揭秘（第四部分）</a></li>
                <li>本文永久链接：<a target="_blank" rel="noopener" href="https://github.com/xitu/gold-miner/blob/master/TODO1/inside-browser-part4.md">github.com/xitu/gold-m…</a></li>
                <li>译者：<a target="_blank" rel="noopener" href="https://github.com/ThomasWhyne">ThomasWhyne</a></li>
                <li>校对者：<a target="_blank" rel="noopener" href="https://github.com/llp0574">llp0574</a> <a target="_blank" rel="noopener" href="https://github.com/CoolRice">CoolRice</a></li>
              </ul>
            </blockquote>
            <h2 id="用户输入行为与合成器"><a href="#用户输入行为与合成器" class="headerlink" title="用户输入行为与合成器"></a>用户输入行为与合成器</h2>
            <p>内部揭秘系列博客对现代浏览器如何处理代码、显示页面展开探讨。该系列博客共四篇，这是最后一篇。在上篇博客里，我们了解了 <a target="_blank" rel="noopener" href="https://developers.google.com/web/updates/2018/09/inside-browser-part3">渲染进程与合成器</a>。这里我们将一窥当用户输入行为发生时，合成器如何继续保障交互流畅。</p>
            <h2 id="浏览器视角下的输入事件"><a href="#浏览器视角下的输入事件" class="headerlink" title="浏览器视角下的输入事件"></a>浏览器视角下的输入事件</h2>
            <p>听到“输入事件”这个字眼，你脑海里闪现的恐怕只是输入文本或点击鼠标。但在浏览器眼中，输入意味着一切用户行为。不单滚动鼠标滑轮是输入事件，触摸屏幕、滑动鼠标同样也是用户输入事件。</p>
            <p>诸如触摸屏幕之类用户手势产生时，浏览器进程会率先将其捕获。然而浏览器进程所掌握的信息仅限于行为发生的区域，因为标签页里的内容都由渲染进程负责处理，所以浏览器进程会将事件类型（如 <code>touchstart</code>）及其坐标发送给渲染进程。渲染进程会寻至事件目标，运行其事件监听器，妥善地处理事件。</p>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/16687fced9601c8b" alt="input event"></p>
            <p>图 1：输入事件由浏览器进程发往渲染进程</p>
            <h2 id="合成器接收输入事件"><a href="#合成器接收输入事件" class="headerlink" title="合成器接收输入事件"></a>合成器接收输入事件</h2>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/16687fdfaf0acaf8" alt="composit.gif"></p>
            <p>图 2：悬于页面图层的视图窗口</p>
            <p>在上篇文章里，我们探讨了合成器如何通过合成栅格化图层，实现流畅的页面滚动。如果页面上没有添加任何事件监听，合成器线程会创建独立于主线程的新合成帧。但要是页面上添加了事件监听呢？合成器线程又是如何得知事件是否需要处理的？</p>
            <h2 id="理解非立即可滚动区"><a href="#理解非立即可滚动区" class="headerlink" title="理解非立即可滚动区"></a>理解非立即可滚动区</h2>
            <p>因为运行 JavaScript 脚本是主线程的工作，所以页面合成后，合成进程会将页面里添加了事件监听的区域标记为“非立即可滚动区”。有了这个信息，如果输入事件发生在这一区域，合成进程可以确定应将其发往主线程处理。如输入事件发生在这一区域之外，合成进程则确定无需等待主线程，可继续合成新帧。</p>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/1668a69b2bd34e88" alt="limited non fast scrollable region"></p>
            <p>图 3：非立即可滚动区输入描述示意图</p>
            <h3 id="设置事件处理器时须注意"><a href="#设置事件处理器时须注意" class="headerlink" title="设置事件处理器时须注意"></a>设置事件处理器时须注意</h3>
            <p>web 开发中常用的事件处理模式是事件代理。因为事件会冒泡，所以你可以在最顶层的元素中添加一个事件处理器，用来代理事件目标产生的任务。下面这样的代码，你可能见过，或许也写过。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">document</span>.body.addEventListener(<span class="string">&#x27;touchstart&#x27;</span>, </span><br><span class="line">event =&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (event.target === area) &#123;</span><br><span class="line">        event.preventDefault();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>这样只需添加一个事件监听器，即可监听所有元素，的确十分省事。然而，如果站在浏览器的角度去考量，这等于把整个页面都标记成了“非立即可滚动区”，意味着即便你设计的应用本不必理会页面上一些区域的输入行为，合成线程也必须在每次输入事件产生后与主线程通信并等待返回。如此则得不偿失，使原本能保障页面滚动流畅的合成器没了用武之地。</p>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/1668a69b2e688711" alt="full page non fast scrollable region"></p>
            <p>图 4：非立即可滚动区覆盖整个页面下的输入描述示意图</p>
            <p>你可以给事件监听添加一个 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#Improving_scrolling_performance_with_passive_listeners"><code>passive:true</code></a> 选项 ，将这种负面效果最小化。这会提示浏览器你想继续在主线程中监听事件，但合成器不必停滞等候，可接着创建新的合成帧。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">document</span>.body.addEventListener(<span class="string">&#x27;touchstart&#x27;</span>, <span class="function"><span class="params">event</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (event.target === area) &#123;</span><br><span class="line">        event.preventDefault()</span><br><span class="line">    &#125;</span><br><span class="line"> &#125;, &#123;<span class="attr">passive</span>: <span class="literal">true</span>&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="检查事件是否可撤销"><a href="#检查事件是否可撤销" class="headerlink" title="检查事件是否可撤销"></a>检查事件是否可撤销</h2>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/1668a69b2c870fb4" alt="page scroll"></p>
            <p>图 5：部分区域仅可水平方向滚动的网页</p>
            <p>设想一下这种情形：页面上有一个盒子，你要将其滚动方向限制为水平滚动。</p>
            <p>为目标事件设置 <code>passive:true</code> 选项可让页面滚动平滑，但在你使用 <code>preventDefault</code> 以限制滚动方向时，垂直方向滚动可能已经触发。使用 <code>event.cancelable</code> 可以检查并阻止这种情况发生。</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">document</span>.body.addEventListener(<span class="string">&#x27;pointermove&#x27;</span>, <span class="function"><span class="params">event</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">if</span> (event.cancelable) &#123;</span><br><span class="line">        event.preventDefault(); <span class="comment">// 阻止默认的滚动行为</span></span><br><span class="line">        <span class="comment">/*</span></span><br><span class="line"><span class="comment">        *  这里设置程序执行任务</span></span><br><span class="line"><span class="comment">        */</span></span><br><span class="line">    &#125; </span><br><span class="line">&#125;, &#123;<span class="attr">passive</span>:: <span class="literal">true</span>&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <p>或者，你也可以应用 <code>touch-action</code> 这类 CSS 规则，完全地将事件处理器屏蔽掉。</p>
            <figure class="highlight css">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="selector-id">#area</span> &#123; </span><br><span class="line">  touch-action: pan-x; </span><br><span class="line">&#125;</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="定位事件目标"><a href="#定位事件目标" class="headerlink" title="定位事件目标"></a>定位事件目标</h2>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/1668a69b295ae0bd" alt="hit test"></p>
            <p>图 6：主线程检查绘制记录查询坐标 x、y 处绘制内容</p>
            <p>合成器将输入事件发送至主线程后，首先运行的是命中检测。命中检测会使用渲染进程中产生的绘制记录数据，找出事件发生坐标下的内容。</p>
            <h2 id="降低往主线程发送事件的频率"><a href="#降低往主线程发送事件的频率" class="headerlink" title="降低往主线程发送事件的频率"></a>降低往主线程发送事件的频率</h2>
            <p>之前的文章里，我们探讨了常见显示屏如何以每秒 60 帧的频率刷新，以及我们要怎样与其刷新频率保持步调一致，以营造出流畅的动画效果。而对于用户的输入行为，常见触摸屏设备的事件传输频率为每秒 60~120 次，常见鼠标设备的事件传输频率为每秒 100 次。可见，输入事件有着比显示屏幕更高的保真度。</p>
            <p>如果一连串 <code>touchmove</code> 这样的事件以每秒 120 次的频率发送往主线程，那么可能会触发过量的命中检测及 JavaScript 脚本执行。相形而言，我们的屏幕刷新率则低下得多。</p>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/1668a69b28e7b10f" alt="unfiltered events"></p>
            <p>图 7：大量事件涌入合成帧时间轴会造成页面闪烁</p>
            <p>为了降低往主线程中传递过量调用，Chrome 会合并这些连续事件（如：<code>wheel</code>, <code>mousewheel</code>, <code>mousemove</code>, <code>pointermove</code>, <code>touchmove</code> 等），并将其延迟至下一次 <code>requestAnimationFrame</code> 前发送。</p>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/1668a69b2dbf1cb4" alt="coalesced events"></p>
            <p>图 8：相同的时间轴下事件被合并且延迟发送</p>
            <p>所有独立的事件，如: <code>keydown</code>, <code>keyup</code>, <code>mouseup</code>, <code>mousedown</code>, <code>touchstart</code>, 及 <code>touchend</code> 则会立即发往主线程。</p>
            <h2 id="使用-getCoalescedEvents-获取帧内事件"><a href="#使用-getCoalescedEvents-获取帧内事件" class="headerlink" title="使用 getCoalescedEvents 获取帧内事件"></a>使用 <code>getCoalescedEvents</code> 获取帧内事件</h2>
            <p>事件合并可帮助大多数 web 应用构建良好的用户体验。然而，如果你开发的是一个绘图类应用，需要基于 <code>touchmove</code> 事件的坐标绘制线路，那么在你试图画下一根光滑的线条时，区间内的一些坐标点也可能会因事件合并而丢失。这时，你可以使用目标事件的 <code>getCoalescedEvents</code> 方法获取事件合并后的信息。</p>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/1668a69be9b80e4c" alt="getCoalescedEvents"></p>
            <p>图 9：左为流畅的触摸手势路径、右为事件合并后的有限路径</p>
            <figure class="highlight js">
              <table>
                <tr>
                  <td class="gutter">
                    <pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre>
                  </td>
                  <td class="code">
                    <pre><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">&#x27;pointermove&#x27;</span>, <span class="function"><span class="params">event</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> events = event.getCoalescedEvents();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">let</span> event <span class="keyword">of</span> events) &#123;</span><br><span class="line">        <span class="keyword">const</span> x = event.pageX;</span><br><span class="line">        <span class="keyword">const</span> y = event.pageY;</span><br><span class="line">        <span class="comment">// 使用 x、y 坐标画线</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre>
                  </td>
                </tr>
              </table>
            </figure>

            <h2 id="后续步骤"><a href="#后续步骤" class="headerlink" title="后续步骤"></a>后续步骤</h2>
            <p>本系列文章里，我们探讨了很多关于 web 浏览器内部的工作原理。如果之前你从来没想过：为什么 Devtools 推荐在事件处理器上添加 <code>&#123;passive:true&#125;</code> 选项、为什么有时须在 script 标签里添加 <code>async</code> 属性？那么我希望这一系列文章能帮助你了解，为什么传递这些信息给浏览器能让其提供更为迅捷流畅的 web 体验。</p>
            <h3 id="使用-Lighthouse"><a href="#使用-Lighthouse" class="headerlink" title="使用 Lighthouse"></a>使用 Lighthouse</h3>
            <p>如果你想构建出对浏览器更为友好的代码，却一直毫无头绪，那么不妨先从使用 <a target="_blank" rel="noopener" href="https://developers.google.com/web/tools/lighthouse/">Lighthouse</a> 开始。Lighthouse 是个可以帮助你审查网站工具，并且能提供页面性能报告。性能报告会告诉你什么地方处理得当，什么地方有待提升。浏览审查列表也能让你了解浏览器着力关注的重点所在。</p>
            <h3 id="学习如何评测性能"><a href="#学习如何评测性能" class="headerlink" title="学习如何评测性能"></a>学习如何评测性能</h3>
            <p>对于不同的站点，桎梏其性能之处可能不尽相同，所以专门为你自己的站点定制化一套性能评测方案，并择优选取技术应用，是重中之重。Chrome 的 Devtools 团队就 <a target="_blank" rel="noopener" href="https://developers.google.com/web/tools/chrome-devtools/speed/get-started">如何测试你的站点性能</a> 撰有相关教程可供参阅。</p>
            <h3 id="为你的站点添加-Feature-Policy"><a href="#为你的站点添加-Feature-Policy" class="headerlink" title="为你的站点添加 Feature Policy"></a>为你的站点添加 Feature Policy</h3>
            <p>如果你想进一步采用更多方案，<a target="_blank" rel="noopener" href="https://developers.google.com/web/updates/2018/06/feature-policy">Feature Policy</a> 是一个新的 web 平台，可在开发时为你保驾护航。开启 feature policy 可以限制应用行为，并使你远离诸多技术弊端。举个例子，如果你想确保应用不会阻塞解析，那么可以采用同步脚本方案运行应用。开启 <code>sync-script:&#39;none&#39;</code> 后，导致解析阻塞的 JavaScript 脚本会被阻止运行。这就确保了你的代码不会阻塞解析，浏览器也无须考虑暂停运行解析器。</p>
            <h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2>
            <p><img src="" data-original="/images/FrontEnd/modern-browser/1668a69bf0a981cc" alt="thank you"></p>
            <p>刚踏上开发之路时，我几乎只关注怎样去写代码、怎样提升自己的生产效率。诚然，这些事情很重要，但与此同时我们也应当思考浏览器会怎么去处理我们书写的代码。现代浏览器一直致力探索如何提供更好的用户体验。书写对浏览器友好的代码，反过来也能提供友好的用户体验。路漫漫其修远兮，希望我们能携手共进，构建出对浏览器更为友好的代码。</p>
            <p>在此笔者诚挚感谢 <a target="_blank" rel="noopener" href="https://twitter.com/slightlylate">Alex Russell</a>、<a target="_blank" rel="noopener" href="https://twitter.com/paul_irish">Paul Irish</a>、<a target="_blank" rel="noopener" href="https://twitter.com/MegginKearney">Meggin Kearney</a>、<a target="_blank" rel="noopener" href="https://twitter.com/ebidel">Eric Bidelman</a>、<a target="_blank" rel="noopener" href="https://twitter.com/mathias">Mathias Bynenes</a>、<a target="_blank" rel="noopener" href="https://twitter.com/addyosmani">Addy Osmani</a>、<a target="_blank" rel="noopener" href="https://twitter.com/kinu">Kinuko Yasuda</a>、<a target="_blank" rel="noopener" href="https://twitter.com/nasko">Nasko Oskov</a> 和 Charlie Reis 等人对本系列文章初稿的校对。</p>
            <p>你喜欢这一系列的文章吗？如对之后文章有任何意见或建议，欢迎在下面评论区或是推特 <a target="_blank" rel="noopener" href="https://twitter.com/kosamari">@kosamari</a> 里留下您的宝贵意见。</p>
            <blockquote>
              <p>如果发现译文存在错误或其他需要改进的地方，欢迎到 <a target="_blank" rel="noopener" href="https://github.com/xitu/gold-miner">掘金翻译计划</a> 对译文进行修改并 PR，也可获得相应奖励积分。文章开头的 <strong>本文永久链接</strong> 即为本文在 GitHub 上的 MarkDown 链接。</p>
            </blockquote>

          </div>





          <footer class="post-footer">
            <div class="post-tags">
              <a href="/tags/FrontEnd/" rel="tag"># FrontEnd</a>
            </div>



            <div class="post-nav">
              <div class="post-nav-item">
                <a href="/blob/2021-06-30-part-3-of-modern-browser/" rel="prev" title="现代浏览器内部揭秘 part 3">
                  <i class="fa fa-chevron-left"></i> 现代浏览器内部揭秘 part 3
                </a>
              </div>
              <div class="post-nav-item">
                <a href="/blob/2021-08-31-the-role-of-webpack-dev-server-host-0.0.0.0/" rel="next" title="webpack-dev-server host 0.0.0.0 的作用">
                  webpack-dev-server host 0.0.0.0 的作用 <i class="fa fa-chevron-right"></i>
                </a>
              </div>
            </div>
          </footer>
        </article>
      </div>







      <script>
        window.addEventListener('tabs:register', () => {
          let {
            activeClass
          } = CONFIG.comments;
          if (CONFIG.comments.storage) {
            activeClass = localStorage.getItem('comments_active') || activeClass;
          }
          if (activeClass) {
            const activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
            if (activeTab) {
              activeTab.click();
            }
          }
        });
        if (CONFIG.comments.storage) {
          window.addEventListener('tabs:click', event => {
            if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
            const commentClass = event.target.classList[1];
            localStorage.setItem('comments_active', commentClass);
          });
        }
      </script>
    </div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


      <div class="copyright">
        &copy;
        <span itemprop="copyrightYear">2021</span>
        <span class="with-love">
          <i class="fa fa-heart"></i>
        </span>
        <span class="author" itemprop="copyrightHolder">holidaypenguin</span>
      </div>
      <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/mist/" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> 强力驱动
      </div>

    </div>
  </footer>


  <script size="300" alpha="0.1" zIndex="-1" src="https://cdn.jsdelivr.net/npm/ribbon.js@1.0.2/dist/ribbon.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js"></script>
  <script src="/js/love.js"></script>

  <script src="/js/development.js"></script>
  <script src="/js/utils.js"></script>
  <script src="/js/motion.js"></script>
  <script src="/js/schemes/muse.js"></script>
  <script src="/js/next-boot.js"></script>


  <script src="/js/local-search.js"></script>









  <script>
    (function() {
      function leancloudSelector(url) {
        url = encodeURI(url);
        return document.getElementById(url).querySelector('.leancloud-visitors-count');
      }

      function addCount(Counter) {
        const visitors = document.querySelector('.leancloud_visitors');
        const url = decodeURI(visitors.id);
        const title = visitors.dataset.flagTitle;

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            if (results.length > 0) {
              const counter = results[0];
              leancloudSelector(url).innerText = counter.time + 1;
              Counter('put', '/classes/Counter/' + counter.objectId, {
                  time: {
                    '__op': 'Increment',
                    'amount': 1
                  }
                })
                .catch(error => {
                  console.error('Failed to save visitor count', error);
                });
            } else {
              Counter('post', '/classes/Counter', {
                  title,
                  url,
                  time: 1
                })
                .then(response => response.json())
                .then(() => {
                  leancloudSelector(url).innerText = 1;
                })
                .catch(error => {
                  console.error('Failed to create', error);
                });
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      function showTime(Counter) {
        const visitors = document.querySelectorAll('.leancloud_visitors');
        const entries = [...visitors].map(element => {
          return decodeURI(element.id);
        });

        Counter('get', '/classes/Counter?where=' + encodeURIComponent(JSON.stringify({
            url: {
              '$in': entries
            }
          })))
          .then(response => response.json())
          .then(({
            results
          }) => {
            for (let url of entries) {
              const target = results.find(item => item.url === url);
              leancloudSelector(url).innerText = target ? target.time : 0;
            }
          })
          .catch(error => {
            console.error('LeanCloud Counter Error', error);
          });
      }

      const {
        app_id,
        app_key,
        server_url
      } = {
        "enable": true,
        "app_id": "povuqNsSqFodlakVIwtEX5kb-gzGzoHsz",
        "app_key": "zXD40RDtDB3DMtpC89k0AK7g",
        "server_url": null,
        "security": false
      };

      function fetchData(api_server) {
        const Counter = (method, url, data) => {
          return fetch(`${api_server}/1.1${url}`, {
            method,
            headers: {
              'X-LC-Id': app_id,
              'X-LC-Key': app_key,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(data)
          });
        };
        if (CONFIG.page.isPost) {
          if (CONFIG.hostname !== location.hostname) return;
          addCount(Counter);
        } else if (document.querySelectorAll('.post-title-link').length >= 1) {
          showTime(Counter);
        }
      }

      const api_server = app_id.slice(-9) === '-MdYXbMMI' ? `https://${app_id.slice(0, 8).toLowerCase()}.api.lncldglobal.com` : server_url;

      if (api_server) {
        fetchData(api_server);
      } else {
        fetch('https://app-router.leancloud.cn/2/route?appId=' + app_id)
          .then(response => response.json())
          .then(({
            api_server
          }) => {
            fetchData('https://' + api_server);
          });
      }
    })();
  </script>



<script>
            window.imageLazyLoadSetting = {
                isSPA: false,
                preloadRatio: 1,
                processImages: null,
            };
        </script><script>window.addEventListener("load",function(){var t=/\.(gif|jpg|jpeg|tiff|png)$/i,r=/^data:image\/[a-z]+;base64,/;Array.prototype.slice.call(document.querySelectorAll("img[data-original]")).forEach(function(a){var e=a.parentNode;"A"===e.tagName&&(e.href.match(t)||e.href.match(r))&&(e.href=a.dataset.original)})});</script><script>!function(n){n.imageLazyLoadSetting.processImages=o;var e=n.imageLazyLoadSetting.isSPA,i=n.imageLazyLoadSetting.preloadRatio||1,r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]"));function o(){e&&(r=Array.prototype.slice.call(document.querySelectorAll("img[data-original]")));for(var t,a=0;a<r.length;a++)0<=(t=(t=r[a]).getBoundingClientRect()).bottom&&0<=t.left&&t.top<=(n.innerHeight*i||document.documentElement.clientHeight*i)&&function(){var t,e,n,i,o=r[a];t=o,e=function(){r=r.filter(function(t){return o!==t})},n=new Image,i=t.getAttribute("data-original"),n.onload=function(){t.src=i,e&&e()},t.src!==i&&(n.src=i)}()}o(),n.addEventListener("scroll",function(){var t,e;t=o,e=n,clearTimeout(t.tId),t.tId=setTimeout(function(){t.call(e)},500)})}(this);</script></body>

</html>